#region The MIT License
// The MIT License
// 
// Copyright (c) 2011 octalforty studios
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using octalforty.Staytuned.ComponentModel;

using Spark;
using Spark.FileSystem;

namespace octalforty.Staytuned.Spark
{
    /// <summary>
    /// An implementation of <see cref="ITemplateRendererModule"/> which uses Spark View Engine to render templates.
    /// </summary>
    public class SparkTemplateRendererModule : ITemplateRendererModule
    {
        #region Private Members
        private readonly string templatesCachePath;
        private readonly SparkViewEngine sparkViewEngine;
        private readonly HashAlgorithm hashAlgorithm;
        private readonly TraceSource traceSource = new TraceSource("SparkTemplateRendererModule", SourceLevels.All);
        #endregion

        /// <summary>
        /// Initializes a new instance of the <see cref="SparkTemplateRendererModule"/> class.
        /// </summary>
        /// <param name="templatesCachePath">Path where templates will be cached.</param>
        public SparkTemplateRendererModule(string templatesCachePath)
        {
            this.templatesCachePath = templatesCachePath;

            var settings = new SparkSettings { PageBaseType = typeof(SparkViewBase).FullName };
            settings.AddAssembly(typeof(IEnumerable<>).Assembly);
            settings.AddAssembly(typeof(Enumerable).Assembly);
            settings.AddNamespace("System");
            settings.AddNamespace("System.Collections");
            settings.AddNamespace("System.Collections.Generic");
            settings.AddNamespace("System.Linq");

            sparkViewEngine = new SparkViewEngine(settings);
            sparkViewEngine.ViewFolder = new FileSystemViewFolder(templatesCachePath);

            hashAlgorithm = new MD5CryptoServiceProvider();
        }

        /// <summary>
        /// Initializes a new instance of the <see cref="SparkTemplateRendererModule"/> class.
        /// </summary>
        /// <remarks>
        /// Uses <see cref="Path.GetTempPath"/> to determine cache path.
        /// </remarks>
        public SparkTemplateRendererModule() :
            this(Path.GetTempPath())
        {
        }

        public string RenderTemplate(string template, IDictionary<string, object> data)
        {
            //
            // Save template to disk. It seems like Spark is unable of not actually using FS
            // to store templates
            var templateFileName = string.Format("{0}.spark", GetTemplateChecksum(template));
            var templatePath = Path.Combine(templatesCachePath, templateFileName);
            
            //
            // Checking if this file already exists. If we'll be overwriting it each time
            // RenderTemplate() is invoked, Spark will be unable to cache it and will
            // recompile template on each invocation. This will make whole thing about 100 times slower.
            if(!File.Exists(templatePath))
                File.WriteAllText(templatePath, template);

            #region Tracing
            traceSource.TraceInformation("Rendering template '{0}' (cached to '{1}')", templateFileName, templatePath);
            var stopwatch = Stopwatch.StartNew();
            #endregion

            var viewDescriptor = new SparkViewDescriptor { Templates = { templateFileName } };
            var view = (SparkViewBase)sparkViewEngine.CreateInstance(viewDescriptor);
            
            try
            {
                foreach(var item in data)
                    view.ViewData.Add(item);

                using(var textWriter = new StringWriter())
                {
                    view.RenderView(textWriter);

                    #region Tracing
                    traceSource.TraceInformation("Rendered template '{0}' in {1}", templateFileName, stopwatch.Elapsed);
                    #endregion

                    return textWriter.ToString();
                } // using
            }
            finally
            {
                sparkViewEngine.ReleaseInstance(view);
            } // finally
        }

        private string GetTemplateChecksum(string template)
        {
            var hash = hashAlgorithm.ComputeHash(Encoding.UTF8.GetBytes(template));
            return BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant();
        }
    }
}